﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Comissoes.Models;
using Comissoes.Utilities;

namespace Comissoes.Controllers
{
    public class ContasController : AppController
    {
        xcontEntities db = new xcontEntities();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="valor"></param>
        /// <param name="condicao"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public JsonResult CalcularParcelas(String valor, String condicao, String data)
        {
            Dictionary<String, String> resultado = new Dictionary<String, String>();

            try
            {
                Decimal Valor = Convertions.Decimal(valor) ?? 0;
                Int32? Condicao = Convertions.Inteiro(condicao);
                DateTime Data = Convertions.Data(data) ?? DateTime.Now;

                IQueryable<DIAS_CONDICAO_PAGAMENTO> d = db.DIAS_CONDICAO_PAGAMENTO.Where(t => t.CONDICOES_PAGAMENTO.COD_CDPG == Condicao).OrderBy(t => t.DIA_DICP);
                Int32 dias = d.Count();
                Int32 dia = 0;

                List<decimal> parcelas = new List<decimal>();

                Decimal resto = Valor - ((Int32)(Valor / dias) * dias);

                foreach (var i in d)
                {
                    if (PeriodosOptions.LastDayOfMonthFromInteger(Data) == 31)
                    {
                        dia++;
                    }

                    if (PeriodosOptions.LastDayOfMonthFromInteger(Data) == 28)
                    {
                        dia = dia - 2;
                    }

                    Decimal parcela = Math.Round((Int32)Valor / dias + resto, 2);
                    resultado.Add(String.Format("{0:dd/MM/yyyy}", Data.AddDays((Double)i.DIA_DICP + dia)), String.Format("{0:C}", parcela));
                    resto = 0;
                }

                return Json(new { result = true, parcelas = resultado }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { result = false }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}